package jblip.gui.data;

import java.util.ArrayList;
import java.util.List;

import jblip.resources.Update;
import jblip.util.UpdateTag;

public class FormattedUpdate {
  private final String formatted_text;

  private final List<UpdateTag> tags;

  public FormattedUpdate(Update update) {
    tags = new ArrayList<UpdateTag>();
    final StringBuilder formatted_update = new StringBuilder(255);
    final StringBuilder next_word = new StringBuilder(31);
    for (char next_char : update.getBody().toCharArray()) {
      if (Character.isWhitespace(next_char)) {
        formatted_update.append(format(next_word.toString()));
        next_word.delete(0, next_word.length());
        formatted_update.append(next_char);
      } else {
        next_word.append(next_char);
      }
    }
    formatted_update.append(format(next_word.toString()));
    formatted_text = formatted_update.toString();
  }

  protected String format(final String word) {
    final UpdateTag tag = UpdateTag.getTag(word);
    if (tag == null) {
      return word;
    } else {
      final int tag_num = tags.size();
      tags.add(tag);
      return formatTag(tag_num, tag);
    }
  }

  protected String formatTag(final int tag_num, final UpdateTag tag) {
    return String.format(
        "<a href=\"tag://%d\" title=\"%s\">%s</a>", tag_num, tag
            .getUserReadableString(), tag.toString());
  }

  public UpdateTag getTag(final String tag_url) {
    if (tag_url.startsWith("tag://")) {
      final int tag_num = Integer.parseInt(tag_url.substring(6));
      return tags.get(tag_num);
    }
    return null;
  }
  
  @Override
  public String toString() {
    return formatted_text;
  }
}
